package com.code.aspect;

import com.code.adapter.LocalDateTimeAdapter;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
 * 日志切面类
 */
@Slf4j
@Aspect
@Component
public class LogAspect {

    /**
     * Controller层前置log输出
     */
    @Pointcut("execution(* com.code.controller.*.*(*))")
    public void logControllerPointCut() {
    }

    /**
     * 标注@SysLog方法的前置log输出
     */
    @Pointcut("@annotation(com.code.annotation.SysLog)")
    public void logSyslogPointCut() {
    }

    @Before("logControllerPointCut()")
    public void around(JoinPoint point) throws Throwable {
        Object[] args = point.getArgs();

        String name = point.getSignature().getDeclaringTypeName();
        if (log.isInfoEnabled()) {
            // log.info("Aspect:" + name + ":{}", JSON.toJSONString(args[0]));
            Gson gson = new GsonBuilder().registerTypeAdapter(LocalDateTime.class, new LocalDateTimeAdapter()).create();
            log.info("Aspect:" + name + ":{}", gson.toJson(args[0]));

        }
    }

    @Before("logSyslogPointCut()")
    public void sysLogBefore(JoinPoint joinPoint) {
        Object[] args = joinPoint.getArgs();
        String name = joinPoint.getSignature().getDeclaringTypeName();
        if (log.isInfoEnabled()) {
            Gson gson = new GsonBuilder().registerTypeAdapter(LocalDateTime.class, new LocalDateTimeAdapter()).create();
            log.info("Aspect:" + name + ":{}", gson.toJson(args[0]));
        }
    }
}
